<template>
  <section class="content" id="content">
    <!-- 检索条件 -->
    <lq-form :form="searchForm" ref="searchFormRef">
      <template #footer>
        <div>
          <el-button type="primary" @click="handleQuery()">查询</el-button>
          <el-button type="warning" size="small" @click="handleExport">导出</el-button>

        </div>
      </template>

    </lq-form>

    <br>
    <!-- 数据列表 -->
    <div id="table">
      <lq-table ref="tableRef"
                :columns="columns"
                :records="tableData.records"
                size="default"
                :border="true"
                :header-cell-style="{background:'#e1eaf6', color:'#333333'}"
                :stripe="true"
                :pagination="paginationProps"
                @on-selections="handleSelectionChange"
                @on-pagination="handleCurrentChange"
      >
        <template #subject="scope">
          <el-link type="primary" @click="handleView(scope.row.id)">{{ scope.row.subject }}</el-link>
        </template>



      </lq-table>
    </div>


    <el-dialog v-model="dialog.visible"
               v-bind="{...dialog.innerAttrs}"
               v-on="dialog.events">
      <EntAccidentForm ref="addEntityFormRef"  @flush="handleFlush"  />

    </el-dialog>


  </section>
</template>
<script setup lang="ts">
/**
 * --------------相关组件引入--------------------------
 */
import {ref, reactive, onMounted, getCurrentInstance, nextTick} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";


import LqForm from "@/pages/components/LqForm.vue";
import LqTable from "@/pages/components/LqTable.vue";
import EntAccidentForm from "@/pages/park/entAccident/EntAccidentForm.vue";


/**
 * --------------全局共享上下文引入--------------------------
 */
const global = getCurrentInstance().appContext.config.globalProperties;


/**
 * ---------------状态变量定义-------------------------
 */
//获取表格组件实例
const tableRef = ref();

//获取新增或编辑窗口组件实例
const addEntityFormRef = ref();


const tableData = ref({
  records: [],
  pageSize: 10,
  tableSize: 'default',
  border: true,
});

//分页信息
const paginationProps = reactive({
  pageSize: tableData.value.pageSize,
  pageSizes: [5, 10, 20, 50, 100],
  total: 0,
  pageNum: 1,
  small: false,
  paginationAlign: 'right',
});


const searchForm = ref({
  innerAttrs: {
    labelPosition: 'right',
    labelWidth:  100,
  },
  model: {
    companyName: "",
    subject: "",
    level: "",
    headName: "",
    headPhone: "",
    time:"",
    createTime:"",
    updateTime:""

  },
  formItems: [
    {type: 'input', label: '企业名称: ', prop: 'companyName', span: 4, maxlength: 30, placeholder: ''},
    {type: 'input', label: '事故事件标题: ', prop: 'subject', span: 4, maxlength: 30, placeholder: ''},
    {type: 'select', label: '事故事件等级: ', prop: 'level', span: 4, options: [{label: '较大事故', value: '较大事故'},{label: '一般事故', value: '一般事故'},{label: '重大事故', value: '重大事故'},{label: '特别重大事故', value: '特别重大事故'}], },
    {type: 'input', label: '企业负责人: ', prop: 'headName', span: 4, maxlength: 30, placeholder: ''},
    {type: 'input', label: '联系电话: ', prop: 'headPhone', span: 4, maxlength: 30, placeholder: ''},
    {type: 'date', label: '事故事件时间: ', prop: 'time', span: 4, maxlength: 30, valueFormat:"YYYY-MM-DD"},
    {type: 'date', label: '提交时间: ', prop: 'createTime', span: 4,valueFormat:"YYYY-MM-DD" },
    {type: 'date', label: '最后修改时间: ', prop: 'updateTime', span: 8,valueFormat:"YYYY-MM-DD" },


  ],
  buttonsAttrs: {
    align: 'left'
  }
});


const columns = [
  {label: '', type: "selection", width: 40},
  {label: '序号', type: "index", width: 50},
  {label: '企业名称', prop: 'companyName', minWidth: 200},
  {label: '事故事件标题', prop: 'subject', slotName: 'subject', slotted: true,minWidth: 120},
  {label: "事故事件等级", prop: 'level', minWidth: 120},
  {label: '事故事件时间', prop: 'time', minWidth: 120},
  {label: "事故概述", prop: 'summary', minWidth: 250},
  {label: "企业负责人", prop: 'headName', minWidth: 110},
  {label: "联系电话", prop: 'headPhone', minWidth: 100},
  {label: "提交人", prop: 'createUser', minWidth: 100},
  {label: "修改人", prop: 'updateUser', minWidth: 100},
  {label: "提交时间", prop: 'createTime', minWidth: 100},
  {label: "最后修改时间", prop: 'updateTime', minWidth: 100},

]


const dialog = ref({
  visible: false,
  innerAttrs: {
    id: 'EntAccidentFormDialog',
    class: 'EntAccidentFormDialog',
    title: '企业事故事件信息',
    width: "60%",
    top: '1vh'
  },
  events: {
    open: () => {
      console.log('dialog open.....');

    },
    close: () => {
      console.log('dialog close.....');

    },
  }
})



/**
 * --------------页面加载生命周期函数--------------------------
 */
onMounted(() => {
  queryData();
})


/**
 * --------------搜索查询功能--------------------------
 */

const handleQuery = () => {
  //每次查询都要从第一页开始
  resetPagination();
  queryData();
}

/**
 * --------------搜索功能--------------------------
 */
const queryData = () => {
  let data = Object.assign({}, searchForm.value.model, {pageNum: paginationProps.pageNum, pageSize: paginationProps.pageSize});
  let obj = global.$delUndefined(data);
  global.$api.getEntAccidentsPage(obj).then(({data}) => {
    if (data.status === 'OK') {
      tableData.value.records = data.data.list;
      paginationProps.total = data.data.total;
      console.log("查询结果",data.data.list)
    }
  });
};

/**
 * --------------刷新--------------------------
 */
const handleFlush = () => {
  dialog.value.visible = false;
  queryData();
}


/**
 * --------------分页操作--------------------------
 */
const handleCurrentChange = () => {
  // 调用查询方法
  queryData();


};


const resetPagination = () => {
  paginationProps.pageNum = 1;
  paginationProps.pageSize = tableData.value.pageSize;
  paginationProps.total = 0;
};

/**
 * --------------编辑--------------------------
 */

const handleEdit = (id: string) => {
  dialog.value.visible = true;
  nextTick(()=>{
    addEntityFormRef.value.handleViewOrEdit(id, false)
  })

}

/**
 * --------------只读--------------------------
 */

const handleView = (id: string) => {
  dialog.value.visible = true;
  nextTick(()=>{
    addEntityFormRef.value.handleViewOrEdit(id, true)
  })


}

/**
 * --------------新增--------------------------
 */

const handleSave = () => {
  //先清空表单，防止编辑污染
  dialog.value.visible = true;
  nextTick(()=>{
    addEntityFormRef.value.handleReset()
  })

}


/**
 * --------------删除操作--------------------------
 */
const handleSingleRemove = (id: string) => {
  ElMessageBox.confirm(`确认要删除吗!`, "确认信息", {
    type: "warning",
    distinguishCancelAndClose: true,
    confirmButtonText: "删除",
    cancelButtonText: "取消",
  })
      .then(() => {
        global.$api
            .deleteEntAccidentsById({
              id: id,
            }).then(({data}) => {
          queryData();
          ElMessage({
            type: "success",
            message: "您已经成功删除了信息",
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "您已经取消了删除操作",
        });
      });

}


/**
 * --------------多选删除操作--------------------------
 */


//选择的记录集
const selections = ref([]);
const handleSelectionChange = (items) => {
  selections.value = items.value.map((item) => item.id);
  // console.log('选择的ID:',...toValue(selections));
}


// 删除功能
const handleBatchRemove = () => {
  if (selections.value.length === 0) {
    ElMessage({
      type: "info",
      message: "请选择至少一个信息记录",
    });
  } else {
    ElMessageBox.confirm(`是否删除${selections.value.length}个从业人员的详细信息？删除后不可恢复!`, "确认信息", {
      type: "warning",
      distinguishCancelAndClose: true,
      confirmButtonText: "删除",
      cancelButtonText: "取消",
    })
        .then(() => {
          global.$api
              .deleteEntAccidentsByIds({
                ids: selections.value,
              }).then(({data}) => {
            queryData();
            ElMessage({
              type: "success",
              message: "您已经成功删除了信息",
            });
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "您已经取消了删除操作",
          });
        });
  }
};


/**
 * --------------定义Excel头部  要跟--------------------------
 */
let tHeader = [
  {name: '企业名称', key: 'companyName'},
  {name: '事故事件标题', key: 'subject'},
  {name: "事故事件等级", key: 'level'},
  {name: '事故事件时间', key: 'time'},
  {name: "事故概述", key: 'summary'},
  {name: "企业负责人", key: 'headName'},
  {name: "联系电话", key: 'headPhone'},
  {name: "提交人", key: 'createUser'},
  {name: "修改人", key: 'updateUser'},
  {name: "提交时间", key: 'createTime'},
  {name: "最后修改时间", key: 'updateTime'},


];


/**
 * --------------导出功能--------------------------
 */
const handleExport = () => {
  let data = Object.assign({},  searchForm.value.model, {});
  let obj = global.$delUndefined(data);
  global.$api.getEntAccidentsList(obj).then(({data}) => {
    if (data.status === 'OK') {
      let exportData = data.data;
      let excelObject = {
        fileName: "企业事故事件信息表", //文件名
        tHeader: tHeader, //生成Excel表格的头部标题栏
        excelData: exportData, //需要导出Excel的数据集合
      };
      global.$exportExcel.exportExcel(excelObject);

    }
  });


};
</script>